package com.ruoyi.web.cp.service.rm;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.ruoyi.web.cp.domain.rm.RmobDx2Merge;
import com.ruoyi.web.cp.domain.rm.RmobDyMerge;
import com.ruoyi.web.mapper.RmobDx2MergeMapper;
import com.ruoyi.web.mapper.RmobDyMergeMapper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class RmobDx2MergeService {

    @Async
    public void saveRmobDx2Merge(List<String> games) {
        RmobDx2Merge rmobMerge = null;
        RmobDx2MergeService service = SpringUtil.getBean("rmobDx2MergeService", RmobDx2MergeService.class);
        for (int i = 0; i < games.size(); i++) {
            String str = games.get(i);
            if (str.startsWith("2025")) {
                String[] strs = str.split(",");
                DateTime date = DateUtil.parse(strs[0], "yyyy-MM-dd HH:mm");

                service.saveOrUpdateByTeamAAndTeamB(rmobMerge);
                rmobMerge = new RmobDx2Merge(strs[4], date, strs[1], strs[2], strs[3]);
            } else {
                String[] strs = str.split("\\|");
                RmobDx2Merge.Detail detail = new RmobDx2Merge.Detail(strs[0], strs[1], strs[2], strs[3]);
                rmobMerge.getDetails().add(detail);
            }
            if (i == (games.size() - 1)) {
                service.saveOrUpdateByTeamAAndTeamB(rmobMerge);
            }
        }
    }

    @Transactional
    public void saveOrUpdateByTeamAAndTeamB(RmobDx2Merge entity) {
        if (entity == null) {
            return;
        }
        RmobDx2MergeMapper rmobDx2MergeMapper = SpringUtil.getBean("rmobDx2MergeMapper", RmobDx2MergeMapper.class);
        // 1. 查询是否已存在记录
        RmobDx2Merge existing = rmobDx2MergeMapper.selectByGameId(entity.getGameId());
        // 2. 如果存在，设置其 ID 以便更新

        if (existing != null) {
            entity.setId(existing.getId());
            rmobDx2MergeMapper.updateRmobDyMerge(entity);
        } else {
            rmobDx2MergeMapper.insertRmobDyMerge(entity);
        }
    }
}
